package com.relax.netty.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        try {
            // 创建 ServerSocket 并绑定端口
            ServerSocket serverSocket = new ServerSocket(8888);

            System.out.println("服务器已启动，等待客户端连接...");

            while (true){
                // 监听客户端连接
                Socket socket = serverSocket.accept();
                new Thread(()->{
                    System.out.println("客户端已连接：" + socket.getInetAddress().getHostAddress());
                    // 获取输入流和输出流
                    BufferedReader reader = null;
                    try {
                        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

                        // 读取客户端发送的数据并进行处理
                        String clientMessage = reader.readLine();
                        System.out.println("客户端消息：" + clientMessage);

                        // 向客户端发送响应数据
                        writer.println("Hello, Client!");
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }


                }).start();
            }




        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
